#! /usr/bin/env python
#
# Author: Gou Pengfei
# Date://05/17/2011 09:04:10 AM (CST)  
#

import sys
import os
import stat
import optparse
import datetime
import re
from subprocess import call
from os.path import join as joinpath
from os.path import isdir, isfile, islink
from os import mkdir,listdir,makedirs
from os import remove
from os import chmod
from shutil import copyfile
from glob import glob

result_dir = joinpath(os.environ['HOME'], 'spec_workdir', 'results',
        'trips', 'linux', 'ref')

backup_dir = joinpath(os.environ['HOME'], 'spec_workdir', 'backup')

optparser = optparse.OptionParser()

optparser.add_option('-b', '--backup', dest='backup',
                     action='store_true',
                     default=False,
                     help='Backup the stats.txt and config.ini'
                     " (default: '%default')" )

optparser.add_option('-c', '--cleanup', dest='cleanup',
                     action='store_true',
                     default=False,
                     help="Cleanup files that are not stats.txt and"
                     "config.ini"
                     " (default: '%default')" )

optparser.add_option('-n', '--config_name', dest='config_name',
                     default="",
                     help='Config name to be manipulated'
                     " (default: '%default')" )
 
(options,leftovers) = optparser.parse_args()

class Workdir(object):
    def __init__(self, bench, config, **kwargs):

        self.bench = bench
        self.config = config

        self.totalFiles = listdir(joinpath(result_dir, bench, config))

        self.subdirs = []
        self.stats = []
        self.configs = []
        self.links = []
        self.others = []

        for f in self.totalFiles:
            f_path = joinpath(result_dir, bench, config, f)
            if islink(f_path):
                self.links.append(f)
            elif isfile(f_path) and f == 'stats.txt':
                self.stats.append(f)
                chmod(f_path, stat.S_IRWXU)
            elif isfile(f_path) and f == 'config.ini':
                self.configs.append(f)
                chmod(f_path, stat.S_IRWXU)
            elif isdir(f_path):
                self.subdirs.append(f)
            else:
                self.others.append(f)

    def cleanup(self):
        '''Remove files that are not stats.txt or config.ini'''
        files_to_remove = self.others + self.links

        for f in files_to_remove: 
            f_path = joinpath(result_dir, self.bench, self.config, f)
#            print 'Remove %s' % f_path
            remove(f_path)

    def backup(self):
        '''Copy stats.txt and config.ini to backup dir'''
        stats_back_dir = joinpath(backup_dir, self.config, 'stats')
        config_back_dir = joinpath(backup_dir, self.config, 'config')

        if not isdir(stats_back_dir) and len(self.stats) > 0:
            makedirs(stats_back_dir)

        if not isdir(config_back_dir) and len(self.configs) > 0:
            makedirs(config_back_dir)

        for f in self.stats:
            src = joinpath(result_dir, self.bench, self.config, f)
            dest = joinpath(stats_back_dir, self.bench + '.txt')
#            print 'Copy %s to %s' % (src, dest)
            copyfile(src, dest)

        for f in self.configs:
            src = joinpath(result_dir, self.bench, self.config, f)
            dest = joinpath(config_back_dir, self.bench + '.ini')
#            print 'Copy %s to %s' % (src, dest)
            copyfile(src, dest)

    def getSubdirs(self):
        return self.subdirs

    def getStats(self):
        return self.stats

    def getConfigs(self):
        return self.configs

    def getLinks(self):
        return self.links

    def getOthers(self):
        return self.others

if __name__ == '__main__':

    benchmarks = listdir(joinpath(result_dir))
    benchmarks.sort()
    
    for bench in benchmarks:
        if options.config_name == "":
            configs = listdir(joinpath(result_dir, bench))
        else:
            configs = options.config_name.split(',')

        configs.sort()
        print configs

        for conf in configs:
            patterns = glob(joinpath(result_dir, bench, conf))

            for pattern in patterns: 

                base_name = os.path.basename(pattern)

                if not isdir(pattern):
                    continue

                if base_name == 'cpt-make-spt-3-2-Omax':
                    continue

                if base_name == 'cpt-make-spt-3-2-Omax-ei':
                    continue

                wd = Workdir(bench, base_name)

                if options.backup:
                    print "Backing up %s for %s" % (base_name, bench)
                    wd.backup()

                if options.cleanup:
                    print "cleaning up %s for %s" % (base_name, bench)
                    wd.cleanup()

